// pages/matches/matches.js
const { get, post } = require('../../utils/api.js')
const { showError, showSuccess, showToast } = require('../../utils/util.js')
const { navigateTo, switchTab } = require('../../utils/router.js')

Page({
  data: {
    // 标签状态
    activeTab: 'likesMe',
    
    // 列表数据
    likesMe: [],         // 喜欢我的
    myLikes: [],         // 我喜欢的
    matches: [],         // 互相匹配
    superLikes: [],      // Super Likes
    
    // 加载状态
    loading: false,
    refreshing: false,
    loadingMore: false,
    
    // 用户详情
    showUserDetail: false,
    selectedUser: null,
    
    // 匹配成功
    showMatchSuccess: false,
    newMatchUser: null,
    userAvatar: null,
    
    // 筛选和排序
    filters: {
      showOnlineOnly: false,
      showVerifiedOnly: false,
      sortBy: 'latest' // latest, distance, compatibility
    },
    showFilterMenu: false,
    
    // 统计数据
    stats: {
      totalLikes: 0,
      totalMatches: 0,
      todayMatches: 0,
      responseRate: 0
    },
    
    // 批量操作
    selectionMode: false,
    selectedUsers: [],
    
    // 连接跟踪
    connectionTracking: {
      lastSeenUsers: [],
      interactionHistory: [],
      qualityScore: 0
    },
    
    // 提醒和通知
    showReminder: false,
    reminderType: '',
    
    // 匹配建议
    showSuggestions: false,
    suggestions: []
  },

  onLoad() {
    this.initPage()
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadAllData()
  },

  /**
   * 初始化页面
   */
  initPage() {
    // 获取用户头像
    const app = getApp()
    const userProfile = app.getUserProfile()
    if (userProfile && userProfile.avatarConfig) {
      this.setData({
        userAvatar: userProfile.avatarConfig
      })
    }
    
    this.loadAllData()
  },

  /**
   * 加载所有数据 - 增强版
   */
  loadAllData() {
    this.setData({ loading: true })
    
    Promise.all([
      this.loadLikesMe(),
      this.loadMyLikes(),
      this.loadMatches(),
      this.loadSuperLikes(),
      this.loadStats(),
      this.loadConnectionTracking()
    ]).then(() => {
      this.generateSuggestions()
      this.checkReminders()
    }).finally(() => {
      this.setData({ 
        loading: false,
        refreshing: false 
      })
    })
  },

  /**
   * 加载喜欢我的用户 - 增强版
   */
  loadLikesMe() {
    return get('/api/matches/likes-me', {
      filters: this.data.filters,
      includeDetails: true
    })
      .then(data => {
        const enhancedUsers = this.enhanceUserData(data.users || [])
        this.setData({
          likesMe: this.sortUsers(enhancedUsers, this.data.filters.sortBy)
        })
      })
      .catch(error => {
        console.error('加载喜欢我的用户失败:', error)
      })
  },

  /**
   * 加载我喜欢的用户 - 增强版
   */
  loadMyLikes() {
    return get('/api/matches/my-likes', {
      filters: this.data.filters,
      includeStatus: true
    })
      .then(data => {
        const enhancedUsers = this.enhanceUserData(data.users || [])
        this.setData({
          myLikes: this.sortUsers(enhancedUsers, this.data.filters.sortBy)
        })
      })
      .catch(error => {
        console.error('加载我喜欢的用户失败:', error)
      })
  },

  /**
   * 加载匹配的用户 - 增强版
   */
  loadMatches() {
    return get('/api/matches/matched', {
      filters: this.data.filters,
      includeChatStatus: true
    })
      .then(data => {
        const enhancedUsers = this.enhanceUserData(data.users || [])
        this.setData({
          matches: this.sortUsers(enhancedUsers, this.data.filters.sortBy)
        })
      })
      .catch(error => {
        console.error('加载匹配用户失败:', error)
      })
  },

  /**
   * 加载 Super Likes
   */
  loadSuperLikes() {
    return get('/api/matches/super-likes')
      .then(data => {
        this.setData({
          superLikes: data.users || []
        })
      })
      .catch(error => {
        console.error('加载 Super Likes 失败:', error)
      })
  },

  /**
   * 加载统计数据
   */
  loadStats() {
    return get('/api/matches/stats')
      .then(data => {
        this.setData({
          stats: {
            totalLikes: data.totalLikes || 0,
            totalMatches: data.totalMatches || 0,
            todayMatches: data.todayMatches || 0,
            responseRate: data.responseRate || 0
          }
        })
      })
      .catch(error => {
        console.error('加载统计数据失败:', error)
      })
  },

  /**
   * 加载连接跟踪数据
   */
  loadConnectionTracking() {
    return get('/api/matches/connection-tracking')
      .then(data => {
        this.setData({
          connectionTracking: {
            lastSeenUsers: data.lastSeenUsers || [],
            interactionHistory: data.interactionHistory || [],
            qualityScore: data.qualityScore || 0
          }
        })
      })
      .catch(error => {
        console.error('加载连接跟踪数据失败:', error)
      })
  },

  /**
   * 增强用户数据
   */
  enhanceUserData(users) {
    return users.map(user => {
      // 计算在线状态
      const isOnline = this.checkOnlineStatus(user.lastActive)
      
      // 计算匹配时间
      const matchedTime = user.matchedAt ? this.getTimeAgo(user.matchedAt) : null
      
      // 计算兼容性评分
      const compatibilityScore = user.compatibilityScore || this.calculateBasicCompatibility(user)
      
      // 获取交互状态
      const interactionStatus = this.getInteractionStatus(user.userId)
      
      return {
        ...user,
        isOnline,
        matchedTime,
        compatibilityScore,
        interactionStatus,
        hasNewMessages: user.unreadCount > 0,
        lastMessagePreview: user.lastMessage ? this.truncateMessage(user.lastMessage) : null
      }
    })
  },

  /**
   * 排序用户
   */
  sortUsers(users, sortBy) {
    switch (sortBy) {
      case 'latest':
        return users.sort((a, b) => new Date(b.matchedAt || b.likedAt) - new Date(a.matchedAt || a.likedAt))
      case 'distance':
        return users.sort((a, b) => (a.distance || 999) - (b.distance || 999))
      case 'compatibility':
        return users.sort((a, b) => (b.compatibilityScore || 0) - (a.compatibilityScore || 0))
      case 'online':
        return users.sort((a, b) => (b.isOnline ? 1 : 0) - (a.isOnline ? 1 : 0))
      default:
        return users
    }
  },

  /**
   * 检查在线状态
   */
  checkOnlineStatus(lastActive) {
    if (!lastActive) return false
    const now = new Date().getTime()
    const lastActiveTime = new Date(lastActive).getTime()
    return (now - lastActiveTime) < 5 * 60 * 1000 // 5分钟内
  },

  /**
   * 获取时间描述
   */
  getTimeAgo(timestamp) {
    const now = new Date().getTime()
    const time = new Date(timestamp).getTime()
    const diff = now - time
    
    const minute = 60 * 1000
    const hour = 60 * minute
    const day = 24 * hour
    
    if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前'
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前'
    } else {
      return Math.floor(diff / day) + '天前'
    }
  },

  /**
   * 计算基础兼容性
   */
  calculateBasicCompatibility(user) {
    // 简化的兼容性计算，基于已有信息
    let score = 70 // 基础分
    
    // 根据认证状态调整
    if (user.isRealNameVerified) score += 5
    if (user.isEducationVerified) score += 5
    if (user.isWorkVerified) score += 5
    
    // 根据资料完整度调整
    if (user.profileCompleteness > 80) score += 10
    
    return Math.min(100, score)
  },

  /**
   * 获取交互状态
   */
  getInteractionStatus(userId) {
    const history = this.data.connectionTracking.interactionHistory
    const userHistory = history.find(h => h.userId === userId)
    
    if (!userHistory) return 'new'
    
    if (userHistory.lastMessageTime) {
      const timeDiff = new Date().getTime() - new Date(userHistory.lastMessageTime).getTime()
      if (timeDiff < 24 * 60 * 60 * 1000) return 'active' // 24小时内
      if (timeDiff < 7 * 24 * 60 * 60 * 1000) return 'recent' // 7天内
      return 'inactive'
    }
    
    return 'matched'
  },

  /**
   * 截断消息
   */
  truncateMessage(message, maxLength = 30) {
    if (message.length <= maxLength) return message
    return message.substring(0, maxLength) + '...'
  },

  /**
   * 标签切换 - 增强版
   */
  onTabChange(e) {
    const activeTab = e.detail.name
    this.setData({ activeTab })
    
    // 记录用户查看行为
    this.trackTabView(activeTab)
    
    // 根据标签加载对应数据
    switch (activeTab) {
      case 'likesMe':
        if (this.data.likesMe.length === 0) {
          this.loadLikesMe()
        }
        break
      case 'myLikes':
        if (this.data.myLikes.length === 0) {
          this.loadMyLikes()
        }
        break
      case 'matches':
        if (this.data.matches.length === 0) {
          this.loadMatches()
        }
        break
      case 'superLikes':
        if (this.data.superLikes.length === 0) {
          this.loadSuperLikes()
        }
        break
    }
  },

  /**
   * 显示筛选菜单
   */
  showFilterMenu() {
    this.setData({ showFilterMenu: true })
  },

  /**
   * 隐藏筛选菜单
   */
  hideFilterMenu() {
    this.setData({ showFilterMenu: false })
  },

  /**
   * 应用筛选
   */
  applyFilters(e) {
    const { filters } = e.detail
    this.setData({ 
      filters: { ...this.data.filters, ...filters },
      showFilterMenu: false
    })
    this.loadAllData()
  },

  /**
   * 更改排序方式
   */
  changeSortBy(e) {
    const sortBy = e.currentTarget.dataset.sortBy
    this.setData({
      'filters.sortBy': sortBy,
      showFilterMenu: false
    })
    
    // 重新排序当前数据
    const { activeTab } = this.data
    switch (activeTab) {
      case 'likesMe':
        this.setData({ likesMe: this.sortUsers(this.data.likesMe, sortBy) })
        break
      case 'myLikes':
        this.setData({ myLikes: this.sortUsers(this.data.myLikes, sortBy) })
        break
      case 'matches':
        this.setData({ matches: this.sortUsers(this.data.matches, sortBy) })
        break
    }
  },

  /**
   * 生成建议
   */
  generateSuggestions() {
    const suggestions = []
    const { stats, likesMe, myLikes, matches } = this.data
    
    // 基于数据生成建议
    if (likesMe.length > 5) {
      suggestions.push({
        type: 'action',
        title: '有多人喜欢您',
        description: `${likesMe.length}个人对您表示了兴趣，去看看吧！`,
        action: 'viewLikesMe',
        priority: 'high'
      })
    }
    
    if (matches.length > 0 && stats.responseRate < 50) {
      suggestions.push({
        type: 'tip',
        title: '提高回复率',
        description: '及时回复消息可以提高匹配成功率',
        action: 'improveResponse',
        priority: 'medium'
      })
    }
    
    if (myLikes.length === 0) {
      suggestions.push({
        type: 'discovery',
        title: '去发现新人',
        description: '在发现页面找到更多有趣的人',
        action: 'goToDiscover',
        priority: 'low'
      })
    }
    
    this.setData({ 
      suggestions,
      showSuggestions: suggestions.length > 0
    })
  },

  /**
   * 检查提醒
   */
  checkReminders() {
    const { matches, connectionTracking } = this.data
    
    // 检查是否有久未回复的匹配
    const inactiveMatches = matches.filter(match => {
      const lastInteraction = connectionTracking.interactionHistory
        .find(h => h.userId === match.userId)
      
      if (!lastInteraction || !lastInteraction.lastMessageTime) {
        return true // 从未聊天
      }
      
      const timeDiff = new Date().getTime() - new Date(lastInteraction.lastMessageTime).getTime()
      return timeDiff > 3 * 24 * 60 * 60 * 1000 // 3天未回复
    })
    
    if (inactiveMatches.length > 2) {
      this.setData({
        showReminder: true,
        reminderType: 'inactive_matches'
      })
    }
  },

  /**
   * 应用建议
   */
  applySuggestion(e) {
    const { action } = e.currentTarget.dataset
    
    switch (action) {
      case 'viewLikesMe':
        this.setData({ activeTab: 'likesMe' })
        break
      case 'goToDiscover':
        this.goToDiscover()
        break
      case 'improveResponse':
        this.showResponseTips()
        break
    }
    
    this.setData({ showSuggestions: false })
  },

  /**
   * 显示回复技巧
   */
  showResponseTips() {
    wx.showModal({
      title: '提高回复率小贴士',
      content: '1. 及时回复消息\n2. 主动开启话题\n3. 分享兴趣爱好\n4. 保持真诚友好',
      showCancel: false,
      confirmText: '我知道了'
    })
  },

  /**
   * 记录标签查看
   */
  trackTabView(tabName) {
    post('/api/matches/track-view', {
      tab: tabName,
      timestamp: new Date().toISOString()
    }).catch(error => {
      console.error('记录查看失败:', error)
    })
  },

  /**
   * 关闭建议
   */
  closeSuggestions() {
    this.setData({ showSuggestions: false })
  },

  /**
   * 关闭提醒
   */
  closeReminder() {
    this.setData({ showReminder: false })
  },

  /**
   * 下拉刷新
   */
  onRefresh() {
    this.setData({ refreshing: true })
    this.loadAllData()
  },

  /**
   * 喜欢回应
   */
  likeBack(e) {
    const userId = e.currentTarget.dataset.userId
    
    post('/api/matches/like-back', { userId })
      .then(data => {
        if (data.isMatch) {
          // 匹配成功
          const user = this.data.likesMe.find(u => u.userId === userId)
          this.setData({
            showMatchSuccess: true,
            newMatchUser: user
          })
          
          // 从喜欢我的列表中移除，添加到匹配列表
          this.moveToMatches(userId)
        }
      })
      .catch(error => {
        console.error('喜欢回应失败:', error)
        showError('操作失败，请重试')
      })
  },

  /**
   * 忽略喜欢
   */
  ignoreLike(e) {
    const userId = e.currentTarget.dataset.userId
    
    wx.showModal({
      title: '确认忽略',
      content: '忽略后将不再显示该用户的喜欢',
      success: (res) => {
        if (res.confirm) {
          post('/api/matches/ignore', { userId })
            .then(() => {
              this.removeFromLikesMe(userId)
              showToast('已忽略')
            })
            .catch(error => {
              console.error('忽略失败:', error)
              showError('操作失败，请重试')
            })
        }
      }
    })
  },

  /**
   * 取消喜欢
   */
  cancelLike(e) {
    const userId = e.currentTarget.dataset.userId
    
    wx.showModal({
      title: '确认取消',
      content: '确定要取消对该用户的喜欢吗？',
      success: (res) => {
        if (res.confirm) {
          post('/api/matches/cancel-like', { userId })
            .then(() => {
              this.removeFromMyLikes(userId)
              showToast('已取消喜欢')
            })
            .catch(error => {
              console.error('取消喜欢失败:', error)
              showError('操作失败，请重试')
            })
        }
      }
    })
  },

  /**
   * 开始聊天
   */
  startChat(e) {
    const userId = e.currentTarget.dataset.userId
    navigateTo(`/pages/chat/chat?userId=${userId}`)
  },

  /**
   * 取消匹配
   */
  unmatch(e) {
    const userId = e.currentTarget.dataset.userId
    
    wx.showModal({
      title: '取消匹配',
      content: '取消匹配后将无法再次与该用户聊天，确定继续吗？',
      confirmText: '确定取消',
      confirmColor: '#ff3b30',
      success: (res) => {
        if (res.confirm) {
          post('/api/matches/unmatch', { userId })
            .then(() => {
              this.removeFromMatches(userId)
              showToast('已取消匹配')
            })
            .catch(error => {
              console.error('取消匹配失败:', error)
              showError('操作失败，请重试')
            })
        }
      }
    })
  },

  /**
   * 查看用户资料
   */
  viewUserProfile(e) {
    const userId = e.currentTarget.dataset.userId
    let user = null
    
    // 从当前标签的列表中找到用户
    switch (this.data.activeTab) {
      case 'likesMe':
        user = this.data.likesMe.find(u => u.userId === userId)
        break
      case 'myLikes':
        user = this.data.myLikes.find(u => u.userId === userId)
        break
      case 'matches':
        user = this.data.matches.find(u => u.userId === userId)
        break
    }
    
    if (user) {
      this.setData({
        showUserDetail: true,
        selectedUser: user
      })
    }
  },

  /**
   * 隐藏用户详情
   */
  hideUserDetail() {
    this.setData({
      showUserDetail: false,
      selectedUser: null
    })
  },

  /**
   * 从详情页忽略
   */
  ignoreLikeFromDetail() {
    const { selectedUser } = this.data
    this.hideUserDetail()
    this.ignoreLike({ currentTarget: { dataset: { userId: selectedUser.userId } } })
  },

  /**
   * 从详情页喜欢回应
   */
  likeBackFromDetail() {
    const { selectedUser } = this.data
    this.hideUserDetail()
    this.likeBack({ currentTarget: { dataset: { userId: selectedUser.userId } } })
  },

  /**
   * 隐藏匹配成功弹窗
   */
  hideMatchSuccess() {
    this.setData({
      showMatchSuccess: false,
      newMatchUser: null
    })
  },

  /**
   * 稍后聊天
   */
  closeMatchSuccess() {
    this.hideMatchSuccess()
  },

  /**
   * 从匹配成功弹窗开始聊天
   */
  startChatFromMatch() {
    const { newMatchUser } = this.data
    this.hideMatchSuccess()
    navigateTo(`/pages/chat/chat?userId=${newMatchUser.userId}`)
  },

  /**
   * 跳转到发现页
   */
  goToDiscover() {
    switchTab('/pages/discovery/discovery')
  },

  // 工具方法
  
  /**
   * 从喜欢我的列表移除
   */
  removeFromLikesMe(userId) {
    const { likesMe } = this.data
    const index = likesMe.findIndex(user => user.userId === userId)
    if (index > -1) {
      likesMe.splice(index, 1)
      this.setData({ likesMe })
    }
  },

  /**
   * 从我喜欢的列表移除
   */
  removeFromMyLikes(userId) {
    const { myLikes } = this.data
    const index = myLikes.findIndex(user => user.userId === userId)
    if (index > -1) {
      myLikes.splice(index, 1)
      this.setData({ myLikes })
    }
  },

  /**
   * 从匹配列表移除
   */
  removeFromMatches(userId) {
    const { matches } = this.data
    const index = matches.findIndex(user => user.userId === userId)
    if (index > -1) {
      matches.splice(index, 1)
      this.setData({ matches })
    }
  },

  /**
   * 移动到匹配列表
   */
  moveToMatches(userId) {
    const { likesMe, matches } = this.data
    const userIndex = likesMe.findIndex(user => user.userId === userId)
    
    if (userIndex > -1) {
      const user = likesMe[userIndex]
      likesMe.splice(userIndex, 1)
      matches.unshift(user) // 添加到匹配列表首位
      
      this.setData({ likesMe, matches })
    }
  },

  /**
   * 分享页面
   */
  onShareAppMessage() {
    return {
      title: '青鸟笺 - 用心灵相遇，让真爱绽放',
      path: '/pages/discovery/discovery',
      imageUrl: '../../images/share-matches.png'
    }
  }
})